<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>医院管理</el-breadcrumb-item>
      <el-breadcrumb-item>药品管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <div slot="header">
        <span>{{ drug_id == '' ? '新增药品' : '编辑药品' }}</span>
      </div>
      <el-form
        :model="drugsForm"
        :rules="drugsFormRules"
        ref="drugsFormRef"
        label-width="150px"
      >
        <el-form-item label="药品名称" prop="title">
          <el-input
            v-model="drugsForm.title"
            placeholder="请输入标准的药品名称，将用于客户端展示"
          ></el-input>
        </el-form-item>
        <el-form-item label="药品分类" prop="category">
          <el-select
            v-model="drugsForm.category"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in classifyData"
              :key="item.id"
              :label="item.name + '【' + item.id + '】'"
              :value="
                typeof drugsForm.category == 'string' ? item.id + '' : item.id
              "
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品规格" prop="spec">
          <div class="dash-border">
            <el-form :model="specForm" :rules="specFormRules" ref="specFormRef">
              <el-row
                v-for="(item, index) in specForm.drugsSpec"
                :key="index"
                :gutter="10"
                style="margin: 10px 0"
              >
                <el-col :span="21">
                  <el-form-item :prop="'drugsSpec.' + index + '.spec'">
                    <el-input
                      v-model="item.spec"
                      placeholder="请输入标准的规格，将用户客户端展示"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <i
                    class="el-icon-plus"
                    @click="addSpec(index)"
                    style="color: #348a5b"
                  ></i>
                  &nbsp;
                  <i
                    class="el-icon-delete"
                    @click="deleteSpec(index)"
                    v-show="index != 0"
                  ></i>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="use_info">
          <el-input
            type="textarea"
            v-model="drugsForm.use_info"
            show-word-limit
            maxlength="500"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="$router.push('/hospital/Drugs')"> 取消 </el-button>
          <el-button
            class="theme-background-color"
            @click="saveAllData"
            :loading="btnLoading"
          >
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  props: {
    drugData: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      drugsForm: {
        title: '',
        category: '',
        spec: '',
        use_info: ''
      },
      drugsFormRules: {
        title: [{ required: true, message: '请输入', trigger: 'blur' }],
        category: [{ required: true, message: '请选择', trigger: 'change' }]
        // spec: [{ required: true, message: '请输入' }]
      },
      classifyData: [],

      specForm: {
        drugsSpec: [{ spec: '' }, { spec: '' }]
      },
      specFormRules: {
        // spec: [{ required: true, message: '请输入', trigger: 'blur' }]
      },

      btnLoading: false,
      drug_id: ''
    }
  },
  created() {
    this.getSelectData()
    console.log(this.$route.query)
    this.initalData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'get_drug_category'
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.classifyData = res.data.get_drug_category
    },
    initalData() {
      const query = this.$route.query
      console.log(JSON.stringify(this.$route.query))
      if (JSON.stringify(this.$route.query) != '{}') {
        for (const key in this.drugsForm) {
          this.drugsForm[key] = query[key]
        }
        let specArray = query.spec.split('；')
        let drugsSpec = []
        specArray.forEach((ele) => {
          drugsSpec.push({ spec: ele })
        })
        this.specForm.drugsSpec = drugsSpec
        console.log(this.drugsForm, this.specForm)
        this.drug_id = query['id']
      }
    },
    addSpec(index) {
      this.specForm.drugsSpec.splice(index + 1, 0, { spec: '' })
    },
    deleteSpec(index) {
      this.specForm.drugsSpec.splice(index, 1)
    },
    // 对部分表单字段进行校验
    validateField(form, index = '') {
      let result = true
      for (let item of this.$refs[form].fields) {
        this.$refs[form].validateField(item.prop, (error) => {
          if (error != '') {
            result = false
          }
        })
        if (!result) break
      }
      return result
    },
    saveAllData() {
      this.$refs.drugsFormRef.validate(async (valid) => {
        if (!valid) return
        // console.log(this.drugsForm)

        // if (!this.validateField('specFormRef')) {
        //   return
        // }
        console.log(this.specForm)
        this.btnLoading = true

        if (this.drug_id == '') {
          // 向后端发起请求
          const { data: res } = await this.$http.post(
            '/admin/drdrug/create',
            this.drugsForm
          )

          if (res.meta.status !== 200) {
            this.btnLoading = false
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('新增药品成功')
        } else {
          this.drugsForm.id = this.drug_id
          // 向后端发起请求
          const { data: res } = await this.$http.post(
            '/admin/drdrug/edit',
            this.drugsForm
          )

          if (res.meta.status !== 200) {
            this.btnLoading = false
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('编辑药品成功')
        }
        this.$router.push('/hospital/Drugs')
        this.btnLoading = false
      })
    }
  },
  watch: {
    'specForm.drugsSpec': {
      handler(val, oldval) {
        let temp = []
        for (let i = 0; i < val.length; i++) {
          temp.push(val[i].spec)
        }
        this.drugsForm.spec = temp.join('@')
      },
      //别忘记开启深度监听
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  .el-select {
    width: 100%;
  }
}
.dash-border {
  border: 1px dashed #dbdbdb;
  padding: 15px;
  margin-bottom: 10px;
}
</style>